package DatagramPlusPlus;


import java.io.IOException;
import java.net.DatagramSocket;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author rafael
 */
public class KeepingAlive implements Runnable {

    private DatagramPlusPlusSocket mainSocket;
    private DatagramReceiver receiver;
    private DatagramSocket s;

    public KeepingAlive(DatagramPlusPlusSocket mainSocket, DatagramReceiver receiver, DatagramSocket socket)   {
        this.mainSocket = mainSocket;
        this.receiver = receiver;
        s = socket;
    }

    public void run() {
        while(true) {
            int dieEm = 2;
            try {
                long myTimeOut, myLastReceived;
                synchronized(mainSocket.timeOut)    {
                    myTimeOut = mainSocket.timeOut;
                }
                synchronized(receiver.ultimoRecebido)   {
                    myLastReceived = receiver.ultimoRecebido;
                }
                wait(myTimeOut);
                synchronized(receiver.ultimoRecebido)   {
                    // Se morreu por timeOut
                    if(dieEm == 0)  {
                        mainSocket.close();
                    }
                    // Se acordou por timeOut
                    if(myLastReceived == receiver.ultimoRecebido)   {
                        dieEm--;
                        // Envia KeepAlive
                        DatagramPlusPlusPacket packet =
                                new DatagramPlusPlusPacket(new DatagramType(DatagramType.KEEP_ALIVE));
                        try {
                            s.send(packet.getUDPPacket());
                        } catch (IOException ex) {
                            System.out.println("Não foi possivel enviar keepAlive.");
                            mainSocket.close();
                        }
                    }
                    else {
                        dieEm = 2;
//                        continue;
                    }
                }

            } catch (InterruptedException ex) {
                
            }
        }
    }
}
